import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import iView from 'iview'
import {getToken, setTitle, setToken} from '@/libs/util'
import config from '@/config'
import authRouteUtl from '../rbac/auth-route-utl'

const {homeName} = config

//解决vue报错NavigationDuplicated
const originalPush    = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
};

Vue.use(Router)
const router               = new Router({
    routes,
    'mode': 'history'
})
const LOGIN_PAGE_NAME      = 'login'
const ROUTE_401_PAGE_NAME  = 'error_401'
const ROUTE_HOME_PAGE_NAME = 'home'

router.beforeEach((to, from, next) => {
    console.log('去-', to.name);
    iView.LoadingBar.start()
    const token = getToken()
    
    if (!token && to.name !== LOGIN_PAGE_NAME) {
        // 未登录且要跳转的页面不是登录页
        next({
            'name': LOGIN_PAGE_NAME // 跳转到登录页
        })
    } else if (!token && to.name === LOGIN_PAGE_NAME) {
        // 未登陆且要跳转的页面是登录页
        next() // 跳转
    } else if (token && to.name === LOGIN_PAGE_NAME) {
        // 已登录且要跳转的页面是登录页
        next({
            'name': homeName // 跳转到homeName页
        })
    } else if (token && to.name === ROUTE_401_PAGE_NAME) {
        // 已登录且要跳转的页面是401页面
        next()
    } else {
        authRouteUtl.setRequestCommonOptions({//rbac请求通用响应头部设置
            headers: {
                Authorization: token
            }
        }).setRequestUrlPre('/api/admin');//rbac请求url前缀设置修改
    
        if (process.env.NODE_ENV === 'development') {
            //开发环境直接跳转，没有必要调取远程路由，因为没有配置 meta.isStatic = true 的页面在正式环境生成文件中都被隐藏，前端正常开发各个页面就行，不必关心权限问题
            return next();
        }
        
        //在页面中包含左侧导航的页面都要走这里，用 auth-route-utl 工具处理导航展示和用户访问权限
        return authRouteUtl
            .responseHookPush('hookKey', (response) => {//rbac所有响应回调钩子添加，可以根据响应状态码来处理token过期等
                console.log('响应钩子触发', response);
                
                //如果http 401,则清空token，跳转到登录页面
                if (response.status === 401) {
                    setToken('');
                    next({
                        name: LOGIN_PAGE_NAME,
                    });
                } else if (response.status === 403) {
                    iView.Message.error('无权获取');
                }
            })
            .getUserPermission(//验证当前导航的访问权限
                to,
                routes,
                () => {//验证通过回调
                    console.log('去', to.name);
                    next();
                },
                () => {//权限验证失败回调
                    console.log('权限验证失败');
                    next({
                        name: ROUTE_401_PAGE_NAME
                    })
                },
                (errResponse) => {//权限接口请求异常回调
                    console.log('权限接口请求异常----', errResponse);
                    
                    //如果http 401,则清空token，跳转到登录页面
                    if (errResponse.status === 401) {
                        setToken('');
                        next({
                            name: LOGIN_PAGE_NAME,
                        });
                    }
                },
            );
    }
})

router.afterEach(to => {
    setTitle(to, router.app)
    iView.LoadingBar.finish()
    window.scrollTo(0, 0)
})

export default router
